/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.prod;

import dp1.titandevelop.titano.bean.Mensajes;
import java.util.List;
import dp1.titandevelop.titano.persistent.*;
import dp1.titandevelop.titano.service.ProcesoService;
import dp1.titandevelop.titano.service.ValidacionService;
import dp1.titandevelop.titano.view.MensajeError;
import java.awt.Dimension;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
/**
 *
 * @author Usuario1
 */
public class ModulosT_PRO_ProcProd extends javax.swing.JInternalFrame {

   public ModulosT_PRO_ProcProdEditar ventanaEdita;
    public List<Zona> zonas;
    public List<Proceso> procesos;
    
    
    
    
    public void RefreshTable() {
        AbstractTableModel aux = (AbstractTableModel)tblResultados.getModel();
        aux.fireTableDataChanged();
    }
    
    public void habilitaBotones(){
        this.btnEditarA.setEnabled(true);
        this.btnEliminarA.setEnabled(true);
    }
    private void inhabilitaBotones(){
        this.btnEditarA.setEnabled(false);
        this.btnEliminarA.setEnabled(false);
    }
     private void addList(List<Zona> lista) {
        for (int i = 0; i < lista.size(); i++) {
            this.cmbzona.addItem(lista.get(i).getDescripcion());
        }
    }
    private AbstractTableModel modeloProcesos = new AbstractTableModel () {

        public int getRowCount() {
            return procesos.size(); // cuantos registros (filas)
        }      
        
        public int getColumnCount() {
            return 3; // cuantas columnas
        }  
        
        String [] titles = {"Zona", "Descripcion", "Cantidad Maquinas"};
        
        @Override
        public String getColumnName(int col){
            return titles[col];
        }        
          
        public Object getValueAt(int rowIndex, int columnIndex) {
            String res=null;
            Proceso p = procesos.get(rowIndex);
            switch(columnIndex){
                case 0: res  = p.getToZona().getDescripcion();
                break;
                case 1: res = p.getDescripcion();
                break;
                case 2: res = ""+ p.getCantidadmaquina();
            }
            return res;
        }  
    };
    public ModulosT_PRO_ProcProd() {
        initComponents();
        ValidacionService val = new ValidacionService();
        this.procesos=new ArrayList<Proceso>();
        
        this.tblResultados.setModel(modeloProcesos);
        inhabilitaBotones();
        
        ProcesoService serv = new ProcesoService();
        zonas = serv.buscarZonaAll();
        addList(zonas);
        val.SSoloLetra(txtLote);
       
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        botonBuscar = new javax.swing.JButton();
        botonNuevo = new javax.swing.JButton();
        botonLimpiar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblResultados = new javax.swing.JTable();
        botonSalir = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        txtLote = new javax.swing.JTextField();
        cmbzona = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        btnEditarA = new javax.swing.JButton();
        btnEliminarA = new javax.swing.JButton();

        setResizable(true);
        setTitle("Administración de Procesos");

        botonBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/buscar.png"))); // NOI18N
        botonBuscar.setToolTipText("Buscar");
        botonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonBuscarActionPerformed(evt);
            }
        });

        botonNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/nuevo.png"))); // NOI18N
        botonNuevo.setToolTipText("Nuevo");
        botonNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonNuevoActionPerformed(evt);
            }
        });

        botonLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/limpiar.png"))); // NOI18N
        botonLimpiar.setToolTipText("Limpiar");
        botonLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonLimpiarActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Resultado de Búsqueda"));
        jPanel2.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        tblResultados.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblResultados.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblResultadosMouseClicked(evt);
            }
        });
        tblResultados.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tblResultadosKeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(tblResultados);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)
                .addContainerGap())
        );

        botonSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/retroceder.png"))); // NOI18N
        botonSalir.setToolTipText("Salir");
        botonSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonSalirActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Filtros de Búsqueda"));
        jPanel1.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        jLabel9.setText("Proceso");

        txtLote.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        cmbzona.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione" }));
        cmbzona.setToolTipText("");
        cmbzona.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbzonaActionPerformed(evt);
            }
        });

        jLabel1.setText("Zona");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel9)
                .addGap(18, 18, 18)
                .addComponent(txtLote, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cmbzona, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(txtLote, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmbzona, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnEditarA.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/editar.png"))); // NOI18N
        btnEditarA.setToolTipText("Editar");
        btnEditarA.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarAActionPerformed(evt);
            }
        });

        btnEliminarA.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/eliminar.png"))); // NOI18N
        btnEliminarA.setToolTipText("Eliminar");
        btnEliminarA.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarAActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addComponent(botonBuscar)
                        .addGap(0, 0, 0)
                        .addComponent(botonNuevo)
                        .addGap(0, 0, 0)
                        .addComponent(botonLimpiar)
                        .addGap(0, 0, 0)
                        .addComponent(botonSalir)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(btnEditarA)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnEliminarA))
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonBuscar)
                    .addComponent(botonNuevo)
                    .addComponent(botonLimpiar)
                    .addComponent(botonSalir))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnEditarA, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnEliminarA, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonNuevoActionPerformed

        ModulosT_PRO.ventanaNuevo = new ModulosT_PRO_ProcProdNuevo();
        this.getParent().add(ModulosT_PRO.ventanaNuevo);
        
        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize = ModulosT_PRO.ventanaNuevo.getSize();
        ModulosT_PRO.ventanaNuevo.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                (desktopSize.height - jInternalFrameSize.height)/4 );
        ModulosT_PRO.ventanaNuevo.show();
        
        this.dispose();
    }//GEN-LAST:event_botonNuevoActionPerformed

    private void botonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonBuscarActionPerformed
        ProcesoService serv = new ProcesoService();
        if (cmbzona.getSelectedIndex()-1==-1){
            procesos = serv.buscarProceso(this.txtLote.getText());
        }else{
            procesos = serv.buscarProceso(this.txtLote.getText(),this.zonas.get(cmbzona.getSelectedIndex()-1).getIdzona());
        }
        

        this.RefreshTable();
    }//GEN-LAST:event_botonBuscarActionPerformed

    private void botonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonLimpiarActionPerformed
       this.txtLote.setText("");
       this.cmbzona.setSelectedIndex(0);
       
       procesos.clear();
       this.RefreshTable();
       this.inhabilitaBotones();
    }//GEN-LAST:event_botonLimpiarActionPerformed

    private void tblResultadosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblResultadosMouseClicked
                                        
        if(evt.getClickCount()==1){
            this.habilitaBotones();
        }
    
        
    }//GEN-LAST:event_tblResultadosMouseClicked

    private void botonSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonSalirActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_botonSalirActionPerformed

    private void tblResultadosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblResultadosKeyPressed
       
    }//GEN-LAST:event_tblResultadosKeyPressed

    private void btnEditarAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarAActionPerformed
        //Obtengo el objeto seleccionado
        Proceso alm;
        alm = procesos.get(this.tblResultados.getSelectedRow());
        //Instancio la ventana
        ventanaEdita = new ModulosT_PRO_ProcProdEditar(alm);
        this.getParent().add(ventanaEdita);

        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize = ventanaEdita.getSize();
        ventanaEdita.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,(desktopSize.height - jInternalFrameSize.height)/4 );
        ventanaEdita.show();

        //Inhabilito los botones una vez realizada la acción
        this.inhabilitaBotones();
    }//GEN-LAST:event_btnEditarAActionPerformed

    private void btnEliminarAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarAActionPerformed
        Mensajes  m = new Mensajes();
        int confirmar = JOptionPane.showInternalConfirmDialog(this.getRootPane(),"¿Está seguro que desea eliminar el proceso, se eliminarán todas las maquinas asociadas al mismo?","Aviso!",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);
        try{
        if (JOptionPane.OK_OPTION == confirmar)
        {//Obtengo el objeto seleccionado
            ProcesoService p = new ProcesoService();
            boolean proc = p.buscarSinProducto(this.tblResultados.getSelectedRow());
            boolean sinemp = p.buscarSinEmpleado(this.tblResultados.getSelectedRow());
            boolean proint = p.buscarsinProdNoIntermedio(this.tblResultados.getSelectedRow());
            
            if (proc && sinemp && proint ){
                Proceso alm;
                alm = procesos.get(this.tblResultados.getSelectedRow());
                this.procesos.remove(alm);
                ProcesoService serv = new ProcesoService();
                serv.eliminarProceso(alm.getIdproceso());
            }else{
                JOptionPane.showInternalMessageDialog(this.getRootPane(), m.getNoEliminadoPorUso(), "Aviso", JOptionPane.WARNING_MESSAGE);

            }
        }
        } catch(Exception e) {
                JOptionPane.showInternalMessageDialog(this.getRootPane(),m.getError(),"Error",JOptionPane.ERROR_MESSAGE);
        }
        this.RefreshTable();
        this.inhabilitaBotones();
    }//GEN-LAST:event_btnEliminarAActionPerformed

    private void cmbzonaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbzonaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbzonaActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonBuscar;
    private javax.swing.JButton botonLimpiar;
    private javax.swing.JButton botonNuevo;
    private javax.swing.JButton botonSalir;
    private javax.swing.JButton btnEditarA;
    private javax.swing.JButton btnEliminarA;
    private javax.swing.JComboBox cmbzona;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable tblResultados;
    private javax.swing.JTextField txtLote;
    // End of variables declaration//GEN-END:variables

    private ProcesoService ProcesoService() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}
